<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" ref="queryForm" label-width="85px">
                <el-row>
                    <el-row>
                        <el-col :span="6">
                            <!-- 厂区-->
                            <el-form-item :label="$t('inspectionManagement.plantArea')" prop="factoryCode">
                                <el-select v-model="queryParams.factoryCode" multiple filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+$t('inspectionManagement.plantArea')">
                                    <el-option v-for="item in factoryOptions" :key="item.plantCode" :label="item.plantName" :value="item.plantCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <!-- 物料选择-->
                            <el-form-item :label="$t('inventoryManagement.materialName')" prop="materialName">
                                <div style="width:215px">
                                    <material-dialog v-model="queryParams.materialName" @callback="(row)=>materialDataCallback(row)" />
                                </div>

                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <!-- 供应商选择-->
                            <el-form-item :label="$t('inventoryManagement.supplierName')" prop="supplierName">
                                <div style="width: 215px">
                                    <supplier-dialog v-model="queryParams.supplierName" @callback="(row)=>supplierDataCallback(row)" />
                                </div>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6" align="left">
                            <!-- 使用决策：-->
                            <el-form-item :label="$t('inventoryManagement.useDecision')" prop="usingDecision">
                                <el-select size="small" v-model="queryParams.usingDecision" multiple :placeholder="$t('public.selectPl')+ $t('inventoryManagement.useDecision')">
                                    <el-option v-for="dict in dict.type.NYIQC_NCR_DECISION" :key="dict.label" :label="dict.label" :value="dict.label" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <!-- 时间范围 -->
                            <el-form-item label="检验结束时间" prop="date">
                                <el-date-picker style="width: 214px" value-format="yyyy-MM-dd" v-model="queryParams.dateRange" type="daterange" :range-separator="$t('structureAnalysis.to')" size="small" :start-placeholder="$t('public.startDate')" :end-placeholder="$t('public.endDate')">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-row>
                <el-row>
                    <el-col align='center'>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('public.query')}}</el-button>
                        <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{$t('public.reset')}}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left">
                    {{$t('defectIncoming.incoming')}}
                </div>
                <div class="header-right">
                    <el-select v-model="queryParams.dateType" @change="dateChange" style="width:80px" size="small" :placeholder="$t('public.selectPl')">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </div>
            </div>

            <el-tabs type="border-card" class="mt10" v-model="activeName" @tab-click="()=>handleTabClick()">
                <el-tab-pane :label="$t('defectIncoming.onePassRate')" name="0">
                    <!-- ecahrt 容器 -->

                    <bar-chart v-if="activeName === '0'" :chartData="chartData" :materialName="queryParams.materialName" height="400px" width="100%" />
                </el-tab-pane>
                <el-tab-pane :label="$t('defectIncoming.twoPassRate')" name="1">
                    <bar-chart v-if="activeName === '1'" :chartData="chartData" :materialName="queryParams.materialName" height="400px" width="100%" />
                </el-tab-pane>
                <el-tab-pane :label="$t('defectIncoming.inspectionTime')" name="2">
                    <time-rate-chart v-if="activeName === '2'" :chartData="chartData" :materialName="queryParams.materialName" height="400px" width="100%" />
                </el-tab-pane>
                <!-- <el-tab-pane :label="$t('defectIncoming.onlineRate')" name="3">
                    <online-rate-chart v-if="activeName === '3'" :materialName="queryParams.materialName" :chartData="chartData" height="400px" width="100%" />
                </el-tab-pane> -->
            </el-tabs>

            <!-- 表格数据 -->
            <!-- <div class="container-header" style="margin-top:10px">
                <div class="header-left">
                    周期一览表
                </div>
            </div>
            <div class="container-table" style="margin-top:20px">
                <el-table max-height="350" border stripe v-loading="loading2" :data="tableList">
                    <el-table-column v-for="(item,index) in columms" :key="index" :label="item.label" :prop="item.prop" show-overflow-tooltip />
                </el-table>
                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getOneTime" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <div class="container-table" style="margin-top:20px">
                <el-table max-height="350" border stripe v-loading="loading" :data="tableList2">
                    <el-table-column v-for="(item,index) in columms2" :key="index" :minWidth="item.minWidth" :label="item.label" :prop="item.prop" show-overflow-tooltip />
                    <el-table-column :label="$t('inventoryManagement.useDecision')" align="left" prop="usingDecision" minWidth="140" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            {{usingDecisionFilter(scope.row)}}
                        </template>
                    </el-table-column>
                    <el-table-column label="检验完成时间" prop="inspectionEndTime" minWidth="160px" show-overflow-tooltip />
                    <el-table-column :label="$t('defectIncoming.unOnlineRate')" prop="onlineUnqualified" minWidth="160px">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.onlineUnqualified" @blur="onlineUnqualifiedBlur(scope.row)" @input="(val)=>{scope.row.onlineUnqualified = val.replace(/[^\d]/g, '')}" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('defectIncoming.inspectResults')" prop="decideResult" minWidth="160px" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.decideResult == '0'">不合格</span>
                            <span v-if="scope.row.decideResult == '1'">合格</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('defectIncoming.ncrNo')" prop="ncrProcessId" minWidth="160px" show-overflow-tooltip />
                    <el-table-column :label="$t('defectIncoming.inspectTime')" prop="timelyInspection" minWidth="160px" show-overflow-tooltip />
                </el-table>
                <pagination v-show="total2>0" :total="total2" :page.sync="queryParams1.pageNum" :limit.sync="queryParams1.pageSize" @pagination="getSMForOneTime" layout="total, sizes, prev, pager, next, jumper" />
            </div> -->
        </div>
    </list-layout>
</template>
<script>
import {
  editUnqualified,
  getOneTimeQualifiedChart,
  getOneTimeQualifiedList,
  getSMForCheckInTimeChart,
  getSMForOneTimeQualifiedListTwo,
  getSMForQualificationChart,
  getSMForTwoTimesQualifiedChart,
} from '@/api/basic/analysiss'

import {getMasterialMaxMinData, listALLMaterialType} from '@/api/basic/materialtype'
import SupplierDialog from '@/views/components/SupplierDialog'
import MaterialDialog from '@/views/components/MaterialDialog'
import BarChart from './BarChart'
import timeRateChart from './timeRateChart.vue'
import onlineRateChart from './onlineRateChart.vue'
import {listALLFactory} from '@/api/basic/factory'

export default {
    name: 'incomingStatistics',
    components: {
        BarChart,
        timeRateChart,
        onlineRateChart,
        SupplierDialog,
        MaterialDialog,
    },
    dicts: [
        'NYIQC_GAUGE_TYPE', //量具类型
        'NYIQC_MATURITY',
        'NYIQC_NCR_DECISION',
    ],
    // components:{Detail},
    data() {
        return {
            materialTypeOptions: [],
            factoryOptions: [], //厂区容器
            // 遮罩层
            loading: false,
            loading2: false,
            // 总条数
            total: 0,
            total2: 0,
            // 字典表格数据
            tableList: [],
            tableList2: [],
            // 弹出层标题
            title: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                plantCode: '',
                materialMax: [],
                materialMiddle: [],
                materialCode: '',
                materialName: '',
                materialType: '',
                maturity: [],
                supplierName: '',
                unit: '',
                usingDecision: [],
                experimentMaterial: '',
                dateRange: [this.getPeriousDate(), this.getNowDate()],
                startTime: '',
                endTime: '',
                dateType: '0',
            },
            queryParams1: {
                pageNum: 1,
                pageSize: 10,
            },
            columms: [
                { label: '日期', prop: 'dateTime', minWidth: '160px' },
                { label: '总批次数', prop: 'totalBatch', minWidth: '160px' },
                { label: '总批数量', prop: 'totalLot', minWidth: '160px' },
                { label: '合格数', prop: 'qualified', minWidth: '160px' },
                { label: '不合格数', prop: 'unqualified', minWidth: '160px' },
                { label: '合格率', prop: 'ratio', minWidth: '160px' },
            ],
            columms2: [
                { label: '到货时间', prop: 'cpudt', minWidth: '160px' },
                { label: '物料编号', prop: 'materialCode', minWidth: '160px' },
                { label: '物料名称', prop: 'materialName', minWidth: '160px' },
                { label: '成熟度', prop: 'maturity', minWidth: '160px' },
                {
                    label: '供应商编号',
                    prop: 'supplierCode',
                    minWidth: '160px',
                },
                { label: '所在厂区', prop: 'factoryName', minWidth: '160px' },
                { label: '物料类型', prop: 'materialType', minWidth: '160px' },
                { label: '供应商批次', prop: 'lichn', minWidth: '160px' },
                { label: '批次', prop: 'lot', minWidth: '160px' },
                { label: '来料数量', prop: 'batchAmount', minWidth: '160px' },
                { label: '单位', prop: 'mengeneinh', minWidth: '160px' },
                { label: '修正数量', prop: 'amendBatch', minWidth: '160px' },
                { label: '修正单位', prop: 'amendMeng', minWidth: '160px' },
            ],
            activeName: '0',
            options: [
                { label: '日', value: '0' },
                { label: '周', value: '1' },
                { label: '月', value: '2' },
                { label: '季', value: '3' },
                { label: '年', value: '4' },
            ],
            chartData: {},
            materialMaxOptions: [],
            materialMiddleOptions: [],
            materialOptions: [],
        }
    },
    created() {
        this.getList()
        this.getFactoryList()
        this.getMaterialType({}, 'materialMax')
        this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
        this.getMaterialType({ materialMiddle: 'all' }, 'typeName')
    },
    methods: {
        filterParams(p) {
            if (p && p.length) {
                return p.join(',')
            } else {
                return ''
            }
        },
        getMaterialType(params, name) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[name])
                if (name === 'materialMax') {
                    this.materialMaxOptions = array
                } else if (name === 'materialMiddle') {
                    this.materialMiddleOptions = array
                } else {
                    this.materialOptions = array
                }
            })
        },
        // 筛选参数
        filterQuery() {
            let params = JSON.parse(JSON.stringify(this.queryParams))
            params.materialMax = this.filterParams(params.materialMax)
            params.materialMiddle = this.filterParams(params.materialMiddle)
            params.maturity = this.filterParams(params.maturity)
            params.usingDecision = this.filterParams(params.usingDecision)
            params.factoryCode = this.filterParams(params.factoryCode)
            if (params.dateRange.length) {
                params.startTime = params.dateRange[0]
                params.endTime = params.dateRange[1]
            } else {
                params.startTime = ''
                params.endTime = ''
            }
            delete params.dateRange
            return params
        },
        filterQuery1() {
            let params = JSON.parse(
                JSON.stringify(
                    Object.assign(
                        {},
                        { ...this.queryParams1 },
                        { ...this.queryParams }
                    )
                )
            )
            params.materialMax = this.filterParams(params.materialMax)
            params.materialMiddle = this.filterParams(params.materialMiddle)
            params.maturity = this.filterParams(params.maturity)
            params.usingDecision = this.filterParams(params.usingDecision)
            params.factoryCode = this.filterParams(params.factoryCode)
            if (params.dateRange.length) {
                params.startTime = params.dateRange[0]
                params.endTime = params.dateRange[1]
            } else {
                params.startTime = ''
                params.endTime = ''
            }
            delete params.dateRange
            return params
        },
        /** 查询字典类型列表 */
        getList() {
            let params = this.filterQuery()
            this.switchTab(params)
            this.getOneTime()
            this.getSMForOneTime()
        },
        getOneTime() {
            this.loading2 = true
            let params = this.filterQuery(this.queryParams)
            // 列表1
            getOneTimeQualifiedList(params).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.tableList = response.rows
                    this.total = response.total
                    this.loading2 = false
                }
            })
        },
        getSMForOneTime() {
            this.loading2 = true
            let params = this.filterQuery1()
            getSMForOneTimeQualifiedListTwo(params).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.tableList2 = response.rows
                    this.total2 = response.total
                    this.loading2 = false
                }
            })
        },
        usingDecisionFilter(row) {
            if (row.usingDecision) {
                let io = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value == row.usingDecision
                })
                return io.label
            } else return ''
        },
        handleMaterialMaxChange(e) {
            this.getMaterialType(
                { materialMax: e.join(',') || 'all' },
                'materialMiddle'
            )
            if (this.queryParams.materialMiddle.length) {
                this.$set(this.queryParams, 'materialMiddle', [])
            }
            if (this.queryParams.materialType) {
                this.$set(this.queryParams, 'materialType', '')
            }
        },
        handleMaterialMiddleChange(e) {
            this.getMaterialType(
                { materialMiddle: e.join(',') || 'all' },
                'typeName'
            )
            if (this.queryParams.materialType) {
                this.$set(this.queryParams, 'materialType', '')
            }
        },
        switchTab(params) {
            const { activeName } = this
            let action
            switch (activeName) {
                case '0':
                    action = getOneTimeQualifiedChart
                    break
                case '1':
                    action = getSMForTwoTimesQualifiedChart
                    break
                case '2':
                    action = getSMForCheckInTimeChart
                    break
                case '3':
                    action = getSMForQualificationChart
                    break
            }
            action(params ? params : this.filterQuery()).then((response) => {
                if (response.code == 200) {
                    this.chartData = response.data
                }
            })
        },
        handleTabClick() {
            this.switchTab()
        },
        // 获取厂区数据
        getFactoryList() {
            listALLFactory().then((res) => {
                this.factoryOptions = res.data
            })
        },
        handleMaterialMessageTypeChange(e) {
            this.queryParams.gaugeType = e.join(',')
        },
        getNowDate() {
            var date = new Date()
            var y = date.getFullYear()
            var m = date.getMonth() + 1
            var d = date.getDate()
            //  当前日期
            return (
                y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
            )
        },
        getPeriousDate() {
            var today = new Date()
            var targetday_milliseconds =
                today.getTime() - 1000 * 60 * 60 * 24 * 30
            today.setTime(targetday_milliseconds) //注意，这行是关键代码
            var tYear = today.getFullYear()

            var tMonth = today.getMonth()

            var tDate = today.getDate()

            tMonth = this.doHandleMonth(tMonth + 1)

            tDate = this.doHandleMonth(tDate)

            return tYear + '-' + tMonth + '-' + tDate
        },
        doHandleMonth(month) {
            var m = month

            if (month.toString().length == 1) {
                m = '0' + month
            }

            return m
        },
        // 表单重置
        reset() {
            this.resetForm('form')
            this.getList()
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 物料选择回调
        materialDataCallback(row) {
            this.queryParams.materialName = row.materialName
            this.queryParams.materialCode = row.materialCode
        },
        // 供应商选择回调
        supplierDataCallback(row) {
            this.queryParams.supplierName = row.supplierName
        },
        materialTypeRemoteMethod(e) {
            listALLMaterialType({ materialTypeName: e }).then((res) => {
                this.materialTypeOptions = res.data
            })
        },
        // 日期格式选择
        dateChange(val) {
            this.switchTab()
            this.getOneTime()
            this.getSMForOneTime()
        },
        //修改来料检验
        onlineUnqualifiedBlur(row) {
            if (row.onlineUnqualified) {
                editUnqualified({
                    id: row.id,
                    onlineUnqualified: row.onlineUnqualified,
                }).then((res) => {
                    if (res.code === 200) {
                        this.$modal.msgSuccess('编辑成功！')
                    }
                })
            }
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
    ::v-deep .el-input__suffix {
        top: 1px;
    }
}
.container-header {
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    //margin-top:6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}

.mt10 ::v-deep .el-tabs__header {
    background-color: #fff;
}
.mt10 ::v-deep .is-active {
    border-top: 1px solid #1890ff;
}
.right-btns ::v-deep .el-button {
    margin-top: 0;
}
.app-container {
    padding: 0;
}
.table-action-wrap {
    padding: 12px 0;
}
</style>
